<template>
  <div
    class="c-wrap"
    v-infinite-scroll="load"
    :infinite-scroll-disabled="disabled"
  >
    <div v-if="contentLoaded" class="container">
      <div class="top-forum-info">
        <router-link :to="{ name: 'forum', params: { id: post.forum.id } }">
          <el-avatar
            shape="square"
            :src="post.forum.avatar"
            :size="50"
          ></el-avatar>
        </router-link>
        <router-link :to="{ name: 'forum', params: { id: post.forum.id } }">
          <h2 class="forum-title">{{ post.forum.forumName }}</h2>
        </router-link>
        <!-- <el-button size="small" icon="el-icon-plus">关注</el-button> -->
        <div class="count d-flex">
          <el-statistic
            group-separator=","
            :value="post.forum.subscribe"
            :value-style="{ fontSize: '12px', color: '#ff7f3e' }"
          >
            <span class="n-prefix" style="white-space: nowrap;" slot="prefix">关注:</span></el-statistic
          >
          <el-statistic
            group-separator=","
            :value="post.forum.postCount"
            :value-style="{ fontSize: '12px', color: '#ff7f3e' }"
          >
            <span class="n-prefix" style="white-space: nowrap;" slot="prefix">文章:</span></el-statistic
          >
        </div>
      </div>
      <el-divider></el-divider>

      <div class="content-wrapper">
        <h1 class="title" style="font-size: 40px">{{ post.title }}</h1>
        <div class="article-n-user">
          <router-link
            :to="{
              name: 'info-center',
              params: { userId: post.author.userId },
            }"
          >
            <avatar :size="50" :user="post.author"></avatar>
          </router-link>
          <div class="info-wrapper">
            <div class="user-about">
              <router-link
                :to="{
                  name: 'info-center',
                  params: { userId: post.author.userId },
                }"
              >
                <span class="nickname">{{ post.author.nickname }}</span>
              </router-link>
              <el-button
                @click="handleFollow"
                v-if="!post.author.isFollowed"
                size="small"
                round
                icon="el-icon-plus"
                >关注</el-button
              >
              <el-button @click="handleFollow" v-else size="small" round
                >取消关注</el-button
              >
              <el-link
                v-if="!isBanned && (auth == 'admin' || auth == 'owner') &&  userInfo.userId != post.author.userId"
                @click="
                  popBanDialog({
                    user: post.author,
                    forumId: post.forum.id,
                  })
                "
                style="margin-left: 20px"
                type="danger"
                >封禁</el-link
              >
              <el-link
                v-if="auth == 'admin' || auth == 'owner' || userInfo.userId == post.author.userId"
                @click="deletePost"
                style="margin-left: 20px"
                type="primary"
                >删除</el-link
              >
            </div>
            <div class="post-about">
              <div class="post-time">{{ post.createTime | dateFormat }}</div>

              <el-statistic
                group-separator=","
                :value="post.viewCount"
                :value-style="{ fontSize: '12px', color: ':#606266' }"
              >
                <span class="n-prefix" slot="prefix">阅读:</span></el-statistic
              >
            </div>
          </div>
        </div>
        <div class="content markdown-body" v-html="contentHtml"></div>
        <div class="post-zan-collection">
          <el-button
            @click="likePost"
            title="点赞"
            circle
            :class="{ active: post.isLike }"
            ><i class="fa fa-thumbs-o-up" aria-hidden="true"></i
          ></el-button>
          <span>{{ post.likeCount }} 人觉得很赞</span>
          <el-button
            style="margin-left: 7px"
            @click="collectPost"
            :class="{ active: post.isCollected }"
            title="收藏"
            circle
            icon="el-icon-star-off"
          ></el-button>
          <span>{{ post.collectCount }} 人收藏了</span>
        </div>
        <el-divider></el-divider>
      </div>

      <div class="comments-area">
        <h2 class="c-title">
          全部评论<span class="c-count">{{ post.commentCount }}</span>
        </h2>
        <div id="do-comment" class="comment-input-wrap d-flex">
          <avatar
            class="user-avatar"
            v-if="isLogin"
            :size="50"
            :user="userInfo"
          ></avatar>
          <comment-input
            @onNewComment="addComment"
            :comment="commentEdit"
          ></comment-input>
          <!-- <div class="ta-container">
          <el-input
            type="textarea"
            rows="6"
            placeholder="请输入内容"
            v-model="comment.content"
            resize="none"
            show-word-limit
          >
          </el-input>
          <div class="ta-op">
            <el-button type="primary" round @click="submitComment">发布</el-button>
            <el-button round @click="comment.content=''">取消</el-button>
          </div>
        </div> -->
        </div>
        <comment-item
          :id="comment.commentId"
          v-for="comment in commentList"
          :key="comment.commentId"
          :comment="comment"
          :post="post"
        ></comment-item>
        <footer-loading :loading="loading" :noMore="noMore"></footer-loading>
      </div>
    </div>
  </div>
</template>

<script>
import { marked } from "marked";
import postApi from "@/axios/postApi";
import CommentItem from "@/components/postItems/CommentItem.vue";
import CommentInput from "@/components/postItems/CommentInput.vue";
import commentApi from "@/axios/commentApi";
import debounceWrapper from "@/commons/debounce";
import FooterLoading from "@/components/CommonItems/FooterLoading.vue";
import userApi from "@/axios/userApi";
import forumApi from "@/axios/forumApi";
import adminApi from "@/axios/adminApi";
import banApi from "@/axios/banApi";
// import "github-markdown-css"
export default {
  components: { CommentItem, CommentInput, FooterLoading },
  props: ["postId"],
  data() {
    return {
      loading: true,
      contentHtml: "",
      contentLoaded: false,
      post: {
        forum: {},
        author: {},
      },
      commentEdit: {
        post: this.$route.params.postId,
        content: "",
        type: 0,
        forum: null,
      },
      commentPage: {
        current: 1,
        size: 5,
        total: 0,
        pages: 0,
      },
      auth: "",
      isBanned: false,
      scrollToCommentId: this.$route.query.refCid,
    };
  },
  computed: {
    noMore() {
      //当不在加载状态并且分页列表为空或者到达尾页时候即显示“没有更多”的提示
      return (
        (this.commentPage.pages == 0 ||
          this.commentPage.pages == this.commentPage.current) &&
        !this.loading
      );
    },
    disabled() {
      return this.noMore || this.loading;
    },
  },

  methods: {
    handleFollow() {
      if (!this.isLogin) return this.popLoginDialog();
      if (this.post.author.isFollowed) {
        userApi.unfollow(this.post.author.userId).then(({ data }) => {
          if (data.code == this.$status.SUCCESS_CODE) {
            this.post.author.isFollowed = false;
            this.$message.success("取消关注成功");
          } else this.$message.error("获取数据时出错");
        });
      } else {
        userApi.follow(this.post.author.userId).then(({ data }) => {
          if (data.code == this.$status.SUCCESS_CODE) {
            this.post.author.isFollowed = true;
            this.$message.success("关注成功");
          } else this.$message.error("获取数据时出错");
        });
      }
    },
    goBack() {
      console.log("go back");
    },
    getPostData(id) {
      postApi.getPostById(id).then(({ data }) => {
        this.post = data.data;
        if (this.post.htmlContent == null)
          this.contentHtml = marked(this.post.content);
        else this.contentHtml = this.post.htmlContent;
        this.commentEdit.forum = this.post.forum.id;
        this.contentLoaded = true;
        document.title = this.post.title
        this.getComments()
        if (!this.isLogin) return;
        adminApi
          .getAuthInfo({ forumId: this.post.forum.id })
          .then(({ data }) => {
            this.auth = data.data;
          });
        banApi
          .getIsBanned({
            userId: this.userInfo.userId,
            forumId: this.post.forum.id,
          })
          .then(({ data }) => {
            this.isBanned = data.data;
          });
      });
    },
    getComments() {
      commentApi
        .getComments({
          ...this.commentPage,
          postId: this.postId,
          cid: this.$route.query.cid,
        })
        .then(({ data }) => {
          this.appendComments(data.data.records);
          this.commentPage.total = data.data.total;
          this.commentPage.pages = data.data.pages;
          //关闭加载动画
          this.loading = false;
          //由于是异步获取评论，所以选择使用事件监听，mounted先监听"scroll"事件，待到
          //数据加载完成再由此处激活事件
          if (this.scrollToCommentId) this.$emit("scroll");
        });
    },
    addComment(comment) {
      this.commentList.push(comment);
    },
    likePost: debounceWrapper(200, function () {
      if (!this.post.isLike)
        postApi.like(this.postId).then(({ data }) => {
          if (data.code == this.$status.SUCCESS_CODE) {
            this.$message.success("点赞成功");
            this.post.isLike = true;
            this.post.likeCount++;
          } else this.$message.error("点赞失败");
        });
      else
        postApi.cacelLike(this.postId).then(({ data }) => {
          if (data.code == this.$status.SUCCESS_CODE) {
            this.$message.success("取消点赞成功");
            this.post.isLike = false;
            this.post.likeCount--;
          } else this.$message.error("取消点赞失败");
        });
    }),
    collectPost: debounceWrapper(200, function () {
      if (!this.post.isCollected)
        postApi.collect(this.postId).then(({ data }) => {
          if (data.code == this.$status.SUCCESS_CODE) {
            this.$message.success("收藏成功");
            this.post.isCollected = true;
            this.post.collectCount++;
          } else this.$message.error("收藏失败");
        });
      else
        postApi.cancelCollect(this.postId).then(({ data }) => {
          if (data.code == this.$status.SUCCESS_CODE) {
            this.$message.success("取消收藏成功");
            this.post.isCollected = false;
            this.post.collectCount--;
          } else this.$message.error("取消收藏失败");
        });
    }),
    load() {
      this.commentPage.current++;
      //开启加载动画
      this.loading = true;
      //让动画加载一会儿再去拉取数据
      setTimeout(() => {
        this.getComments();
      }, 300);
    },
    deletePost() {
      let confirm = window.confirm("确认删除此篇文章？");
      if (!confirm) return;
      postApi.deletePost(this.postId).then((r) => {
        this.$message.success("删除成功");
        this.$router.replace({
          name: "forum",
          params: { id: this.post.forum.id },
        });
      });
    },
  },
  created() {
    console.log(this.postId)
    this.getPostData(this.postId);
  },
  beforeRouteUpdate(to, from, enter) {
    this.purgeCommentList();
    this.getPostData(to.params.postId);
  },
  mounted() {
    this.$on("scroll", () => {
      //此处必须用nextTick回调，因为需要待到dom更新完成再滑动
      this.$nextTick(() => {
        document.getElementById(this.scrollToCommentId).scrollIntoView();
        this.scrollToCommentId = null;
      });
    });
  },
  beforeDestroy() {
    this.purgeCommentList();
  },
};
</script>
<style scoped lang="less">
.c-wrap {
  height: 100%;
  overflow-y: scroll;
}
.container {
  width: 1000px;

  margin: 0 auto;
  .top-forum-info {
    background: #f4f6f9;
    display: flex;
    align-items: center;
    height: 100px;

    padding-left: 50px;
    & > * {
      margin-right: 20px;
    }
  }
  .content-wrapper {
    padding: 20px;
    background: #fff;
    border-radius: 10px;

    .article-n-user {
      color: #606266;
      font-size: 14px;
      padding: 20px 0;
      display: flex;
      align-items: center;
      .el-avatar {
        margin-right: 20px;
      }
      .info-wrapper {
        display: flex;
        flex-direction: column;
        .n-prefix {
          color: #606266;
          white-space: nowrap;
        }
        .user-about {
          margin-bottom: 10px;
          .nickname {
            margin-right: 10px;
          }
        }
        .post-about {
          display: flex;

          & > * {
            margin-right: 10px;
          }
          .post-time {
            white-space: nowrap;
            line-height: 22px;
          }
        }
      }
    }
  }
}
.comment-input-wrap {
  .user-avatar {
    margin-right: 30px;
    flex-shrink: 0;
  }
  .ta-container {
    width: 100%;
    .ta-op {
      margin-top: 10px;
      display: flex;
      justify-content: flex-end;
      & > .el-button {
        margin-right: 5px;
      }
    }
  }
}

.post-zan-collection {
  margin-top: 20px;
  .el-button {
    &:focus {
      background: #fff;
      border: 1px solid #dcdfe6;
      color: #606266;
    }
    &.active {
      color: #409eff;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
    margin-right: 10px;
  }
}
.comments-area {
  padding: 40px;
  margin-top: 20px;
  background: #fff;
  border-radius: 10px;
  .c-title {
    border-left: 4px solid var(--text-primary);
    padding-left: 10px;
    margin-bottom: 20px;
    .c-count {
      font-size: 20px;
      margin-left: 7px;
      color: var(--text-regular);
    }
  }
}
</style>